package com.client.window;

import com.client.service.OICQClient;
import com.client.service.ServerHandler;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author e4glet
 * 2025年3月5日
 * */

// 主窗口
public class MainWindow extends JFrame {
    private JList<String> friendList;
    private DefaultListModel<String> friendListModel;
    private JButton addFriendButton;
    private JButton addGroupButton;
    private OICQClient client; // 添加OICQClient实例变量
    private ServerHandler serverHandler;
    private Thread serverThread;
    // 新建Map存储好友的未读消息数,实例化使用线程安全的HashMap集合 键: 好友ID, 值: 未读消息数
    private Map<Integer,Integer> unreadMessages = new ConcurrentHashMap<>();
    // 新增: 存储好友ID对应的最新消息
    private Map<Integer, String> latestMessages = new ConcurrentHashMap<>();
    // 存储当前打开的聊天窗口，键: 好友ID，值: 窗口实例
    private Map<Integer, ChatWindow> openChatWindows = new ConcurrentHashMap<>();

    // 添加自定义的好友列表渲染器，包括显示未读消息数
    private class FriendListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, 
                int index, boolean isSelected, boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);
            
            String text = value.toString();
            String[] parts = text.split(" ");
            int friendId = Integer.parseInt(parts[0]);
            int unread = unreadMessages.getOrDefault(friendId, 0);
            // 示例显示效果: "1 ming [在线] (2)"
            String status = text.contains("[在线]") ? "[在线]" : "[离线]";
            String displayText = parts[0] + " " + parts[1] + " " + status;
            if (unread > 0) {
                displayText += " (" + unread + ")";
            }
            label.setText(displayText);

            if (text.contains("[离线]")) {
                label.setForeground(isSelected ? Color.LIGHT_GRAY : Color.GRAY);
            } else {
                label.setForeground(isSelected ? Color.WHITE : Color.BLACK);
            }
            
            return label;
        }
    }

    /**
     * 用户主窗口
     * client 是登录时的socket对象
     *
     * */
    public MainWindow(OICQClient client) { // 构造函数中初始化client
        this.client = client;
//        System.out.println("传递过来的client："+client);
        setTitle("OICQ主窗口");
        setSize(400, 900);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());
        add(panel);

        friendListModel = new DefaultListModel<>();
        friendList = new JList<>(friendListModel);
        panel.add(new JScrollPane(friendList), BorderLayout.CENTER);

        // 在friendList初始化后添加自定义渲染器
        friendList.setCellRenderer(new FriendListRenderer());

        JPanel buttonPanel = new JPanel();
        addFriendButton = new JButton("添加好友");
        addGroupButton = new JButton("添加群");
        buttonPanel.add(addFriendButton);
        buttonPanel.add(addGroupButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 添加添加好友按钮事件处理
        addFriendButton.addActionListener(e -> {
            String account = JOptionPane.showInputDialog("请输入要添加好友的QQ号或邮箱:");
            if (account != null && !account.isEmpty()) {
                try {
                    String response = client.searchUserByEmail(account);
                    if (response != null && response.startsWith("SEARCH_USER_SUCCESS")) {
                        String[] parts = response.split(" ");
                        if (parts.length >= 3) {
                            int friendId = Integer.parseInt(parts[1]);
                            String nickname = parts[2];
                            int confirm = JOptionPane.showConfirmDialog(null, 
                                "找到用户: " + nickname + "\n是否添加好友?", 
                                "添加好友确认", 
                                JOptionPane.YES_NO_OPTION);
                            if (confirm == JOptionPane.YES_OPTION) {
                                try {
                                    if (client.addFriend(client.getUserId(), friendId)) {
                                        JOptionPane.showMessageDialog(null, "好友添加成功");
                                        updateFriendListFromServer(); // 立即更新好友列表
                                    } else {
                                        JOptionPane.showMessageDialog(null, "好友添加失败");
                                    }
                                } catch (IOException ex) {
                                    if (ex.getMessage().equals("Friend already exists")) {
                                        JOptionPane.showMessageDialog(null, "该用户已经是您的好友");
                                    } else {
                                        JOptionPane.showMessageDialog(null, "添加好友失败: " + ex.getMessage());
                                    }
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "未找到用户");
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "搜索失败: " + ex.getMessage());
                }
            }
        });

        // 添加双击好友列表事件处理，打开时加载消息并清除未读计数
        friendList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    String selected = friendList.getSelectedValue();
                    if (selected != null) {
                        String[] parts = selected.split(" ");
                        int friendId = Integer.parseInt(parts[0]);
                        String friendName = parts[1];

                        // 获取并清除最新消息
                        String latestMessage = getAndClearLatestMessage(friendId);

                        // 打开聊天窗口并显示最新消息
                        new ChatWindow(client, friendName, friendId, latestMessage, MainWindow.this);

                        // 清除未读计数
                        unreadMessages.put(friendId, 0);
//                        updateFriendListFromServer();
                    }
                }
            }
        });

        // 替换Timer为多线程
        serverHandler = new ServerHandler(client, this);
        serverThread = new Thread(serverHandler);
        serverThread.start();

        // 修改窗口关闭事件处理
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                try {
                    serverHandler.stop();  // 停止服务器处理线程
                    if (serverThread != null) {
                        serverThread.interrupt();
                    }
                    client.logout();
                    client.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                System.exit(0);
            }
        });

        setVisible(true);
    }

    // 打开聊天窗口后，将好友消息添加到聊天框内
    public void setLatestMessage(int friendId, String message) {
        latestMessages.put(friendId, message);
    }

    // 获取完成后移除好友消息
    public String getAndClearLatestMessage(int friendId) {
        return latestMessages.remove(friendId); // 取出后清除
    }

    // 修改更新好友列表方法
    public void updateFriendListFromServer() {
        try {
            String response = client.getFriendList();
            System.out.println("收到服务器响应：" + response);
            if (response != null && response.startsWith("FRIEND_LIST")) {
                SwingUtilities.invokeLater(() -> {
                    friendListModel.clear();
                    String[] friends = response.substring(12).split(";");
                    for (String friend : friends) {
                        if (!friend.isEmpty()) {
                            String[] parts = friend.split(",");
                            if (parts.length >= 3) {
                                String id = parts[0];
                                String nickname = parts[1];
                                String status = parts[2].equals("1") ? "[在线]" : "[离线]";
                                friendListModel.addElement(id + " " + nickname + " " + status);
                            }
                        }
                    }
                    friendList.repaint();
                });
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "更新好友列表失败");
        }
    }

    /**
     * 更新未读消息计数方法
     * */
    public void incrementUnreadCount(int friendId) {
        unreadMessages.put(friendId, unreadMessages.getOrDefault(friendId, 0) + 1);
        updateFriendListFromServer(); // 刷新好友列表显示？？只需要渲染好友列表渲染器即可。后期优化
    }

    /**
     * 添加聊天窗口到 Map
     * */
    public void addOpenChatWindow(int friendId, ChatWindow window) {
        openChatWindows.put(friendId, window);
    }

    // 移除聊天窗口
    public void removeOpenChatWindow(int friendId) {
        openChatWindows.remove(friendId);
    }

    // 检查聊天窗口是否已打开
    public boolean isChatWindowOpen(int friendId) {
        return openChatWindows.containsKey(friendId);
    }

    // 获取聊天窗口实例
    public ChatWindow getChatWindow(int friendId) {
        return openChatWindows.get(friendId);
    }
}
